package randid

import (
	"crypto/rand"
	"encoding/hex"
)

type RandIdGetter interface {
	Get() (string, error)
}

type RandIdGetterFunc func() string

func (fn RandIdGetterFunc) Get() string {
	return fn()
}

// SecureRandom 基于hex算法生成指定长度的随机字符串
type SecureRandom struct {
	Length int
}

func NewSecureRandom(length int) RandIdGetter {
	return &SecureRandom{Length: length / 2}
}

func NewDefaultSecureRandom() RandIdGetter {
	return &SecureRandom{Length: 4}
}

func (r *SecureRandom) Get() (string, error) {
	bytes, err := r.randomBytes()
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}

func (r *SecureRandom) randomBytes() ([]byte, error) {
	bytes := make([]byte, r.Length)
	_, err := rand.Read(bytes)
	if err != nil {
		return nil, err
	}
	return bytes, nil
}
